package com.zy.storage

import android.content.Context
import com.google.gson.Gson
import com.zy.storage.doc.DocInfo
import com.zy.storage.doc.DocInfoDao
import com.zy.storage.doc.LocalDocInfo
import com.zy.utils.ThreadUtils
import com.zy.zlog.ZLog

object DataBaseUtils {

    private lateinit var db: ZYDatabase

    fun init(context: Context) {
        db = ZYDatabase.getDatabase(context)
        ThreadUtils.ioRun {
            val list = db.docDao().getAll()
            if (list.isEmpty()) {
                initData()
            }
        }

        ThreadUtils.ioPostDelayed(2000) {
            val dao = db.docDao()
            val allList = dao.getAll()
            ZLog.i("DataBaseUtils", "allList:" + allList.size)
            val allListStr = Gson().toJson(LocalDocInfo(allList.size, allList))
            ZLog.i("DataBaseUtils", "allListStr:$allListStr")
        }
    }

    fun add(docInfo: DocInfo) {
        ThreadUtils.ioRun {
            db.docDao().insertAll(docInfo)
        }
    }

    fun copy(docInfo: DocInfo) {
        ThreadUtils.ioRun {
            val title = docInfo.title + " " + System.currentTimeMillis()
            val newDocInfo = DocInfo(
                parentId = docInfo.parentId,
                fileId = System.currentTimeMillis(),
                title = title,
                des = docInfo.des,
                fileType = docInfo.fileType,
                layout = docInfo.layout
            )
            db.docDao().insertAll(newDocInfo)
        }
    }

    fun delete(docInfo: DocInfo) {
        ThreadUtils.ioRun {
            db.docDao().delete(docInfo)
        }
    }

    fun update(docInfo: DocInfo) {
        ThreadUtils.ioRun {
            db.docDao().update(docInfo)
        }
    }

    fun getDocInfoDao(): DocInfoDao = db.docDao()

    private fun initData() {
        //根目录
        val docDao = db.docDao()
        //val baseList = Gson().fromJson(BaseInfoData.DATA_20231020, LocalDocInfo::class.java).list
        val baseList = Gson().fromJson(BaseInfoData.DATA_20231105, LocalDocInfo::class.java).list
        baseList.forEach {
            docDao.insertAll(it)
        }
    }
}